package com.example.javamaday.leetcode;

import com.example.javamaday.leetcode.base.ListNode;

public class LeetCodeTest0160 {

    public static void main(String[] args) {

    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {

        ListNode a = headA;
        int lengthA = 0;
        while (a != null) {
            a = a.next;
            lengthA++;
        }
        ListNode b = headB;
        int lengthB = 0;
        while (b != null) {
            b = b.next;
            lengthB++;
        }

        int num = lengthB - lengthA;
        if (num > 0) {
            while (headB != null && num > 0) {
                headB = headB.next;
                num--;
            }
        } else if (num < 0) {
            while (headA != null && num < 0) {
                headA = headA.next;
                num++;
            }
        }
        while (headA != null || headB != null) {
            if (headA == headB) {
                return headA;
            } else {
                if (headA != null && headB != null) {
                    headA = headA.next;
                    headB = headB.next;
                } else {
                    break;
                }

            }
        }
        return null;
    }


}
